package wxapp

import (
	"sync"
	"time"
)

type TokenInfo struct {
	Token 			string
	ExpireTime     	int64
}

type TokenCache struct {
	tokens 	map[string]TokenInfo
	lock   	sync.Mutex
}

var token_cache TokenCache
func GetAccessToken(appid string, secret string) (string, error) {
	return token_cache.GetAccessToken(appid, secret)
}

func (cache *TokenCache) GetAccessToken(appid string, secret string) (string, error) {
	cache.lock.Lock()
	defer cache.lock.Unlock()

	if cache.tokens == nil {
		cache.tokens = make(map[string]TokenInfo)
	}

	tm := time.Now().Unix()
	info, ok := cache.tokens[appid]
	if ok == false || tm >= info.ExpireTime {
		ret, err := getAccessToken(appid, secret)
		if err != nil {
			return "" ,err
		}
		info.Token = ret.AccessToken
		info.ExpireTime = tm + ret.ExpiresIn
		cache.tokens[appid] = info
		return info.Token, nil
	} else {
		return info.Token, nil
	}
}
